package com.cxd.web.backend;

import com.cxd.entity.EbProductCategory;
import com.cxd.entity.EbUser;
import com.cxd.service.IEbProductCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/productCategory")
public class ProductCategoryController {
    @Autowired
    private IEbProductCategoryService iEbProductCategoryService;
    /**
     * 实现产品分类项分页查询功能
     * model：用于返回分页查询结果
     * page：用于获取要访问的页数（默认值：1）
     * pageSize：用于获取每页显示多少条（默认值：10）
     */
    @GetMapping("/list")
    public String list(HttpSession session, Model model, @RequestParam(value = "page",defaultValue = "1") int page, @RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        Object user = session.getAttribute("lgnUser");
        if (user == null){
            return "redirect:/f-login/to_login";
        }
        EbUser ebUser = (EbUser) user;
        if(ebUser.getEuStatus()!=2){
            return "redirect:/f-index/index";
        }
        model.addAttribute("user",ebUser);
        /*
        * 由于产品分类表父类子类混在一起，正常分页查询将得到混乱的视图。
        * 同时产品分类不可能特别多，为了获得好的页面效果，
        * 本方法先获取数据库中所有项（ebProductCategories），然后抽出所有父类（parentCategory）
        * 按第一个父类---此父类所有子类---第二个第二个父类顺序重新排列（orderlyCategory）
        * 再进行分页（outList）*/
        List<EbProductCategory> ebProductCategories = iEbProductCategoryService.listByPage();
        Integer totalPage = iEbProductCategoryService.findTotalPage(pageSize);
        List<EbProductCategory> parentCategory = new ArrayList<>();
        List<EbProductCategory> orderlyCategory = new ArrayList<>();
        List<EbProductCategory> outList = new ArrayList<>();
        for (int i = 0;i < ebProductCategories.size();++i){
            if(ebProductCategories.get(i).getEpcId()==ebProductCategories.get(i).getEpcParentId()){
                parentCategory.add(ebProductCategories.get(i));
                orderlyCategory.add(ebProductCategories.get(i));
                for (int m = 0;m < ebProductCategories.size();++m){
                    if (ebProductCategories.get(i).getEpcId()==ebProductCategories.get(m).getEpcParentId()
                            &&ebProductCategories.get(m).getEpcId()!=ebProductCategories.get(m).getEpcParentId()){
                        orderlyCategory.add(ebProductCategories.get(m));
                    }
                }
            }
        }
        int i = (page - 1) * pageSize;
        if (orderlyCategory.get(i).getEpcId() != orderlyCategory.get(i).getEpcParentId()){
            for(int m = 0;m < parentCategory.size();++m){
                if (parentCategory.get(m).getEpcId() == orderlyCategory.get(i).getEpcParentId()){
                    outList.add(parentCategory.get(m));
                    break;
                }
            }
            for (int m = i;m < orderlyCategory.size() && m < i + pageSize - 1;++m){
                outList.add(orderlyCategory.get(m));
            }
        }else {
            for (int m = i;m < orderlyCategory.size() && m < i + pageSize;++m){
                outList.add(orderlyCategory.get(m));
            }
        }
        //分页查询结果
        model.addAttribute("list",outList);
        //当前页
        model.addAttribute("currPage",page);
        //总页数
        model.addAttribute("totalPage",totalPage);
        model.addAttribute("tag",3);
        return "manage/productClass";
    }
    /**
     * 实现访问产品分类项添加页面功能
     * model：用于返回数据库中全部项
     */
    @GetMapping("/productClass_add")
    public String toSave(HttpSession session,Model model){
        Object user = session.getAttribute("lgnUser");
        if (user == null){
            return "redirect:/f-login/to_login";
        }
        EbUser ebUser = (EbUser) user;
        if(ebUser.getEuStatus()!=2){
            return "redirect:/f-index/index";
        }
        model.addAttribute("user",ebUser);
        List<EbProductCategory> ebProductCategories = iEbProductCategoryService.listByPage();
        model.addAttribute("ebProductCategory",ebProductCategories);
        model.addAttribute("tag",3);
        return "manage/productClass-add";
    }
    /**
     * 实现分类项添加功能
     * model用于返回操作结果（影响行数）
     * ebProductCategory用于获得要添加项的实体对象
     * 如果父类值为0，则此项修改为父类
     */
    @PostMapping("/productClass_add")
    public String save(HttpSession session,Model model,EbProductCategory ebProductCategory){
        Object user = session.getAttribute("lgnUser");
        if (user == null){
            return "redirect:/f-login/to_login";
        }
        EbUser ebUser = (EbUser) user;
        if(ebUser.getEuStatus()!=2){
            return "redirect:/f-index/index";
        }
        model.addAttribute("user",ebUser);
        if (ebProductCategory.getEpcName().trim().length() == 0){
            model.addAttribute("result",0);
            model.addAttribute("tag",3);
            return "manage/manage-result";
        }
        int num = iEbProductCategoryService.save(ebProductCategory);
        /*
         * 如果要将此项要作为父类，则保持此项后，将此项父类设置为自己
         */
        if (num == 1 && ebProductCategory.getEpcParentId() == 0){
            EbProductCategory ebProductCategory1 = iEbProductCategoryService.selectByName(ebProductCategory.getEpcName());
            ebProductCategory1.setEpcParentId(ebProductCategory1.getEpcId());
            num = iEbProductCategoryService.updateById(ebProductCategory1);
        }
        System.out.println(num);
        model.addAttribute("result",num);
        model.addAttribute("tag",3);
        return "manage/manage-result";
    }
    /**
     * 实现访问产品分类项修改页面功能
     * model："ebProductCategories"用于返回数据库中全部项
     * model："ebProductCategory"用于返回要修改项
     * epcId用于获得要修改项的id
     */
    @GetMapping("/productClass-modify")
    public String toModify(HttpSession session,Model model,int epcId){
        Object user = session.getAttribute("lgnUser");
        if (user == null){
            return "redirect:/f-login/to_login";
        }
        EbUser ebUser = (EbUser) user;
        if(ebUser.getEuStatus()!=2){
            return "redirect:/f-index/index";
        }
        model.addAttribute("user",ebUser);
        EbProductCategory ebProductCategory = iEbProductCategoryService.selectByCondition(epcId);
        List<EbProductCategory> ebProductCategories = iEbProductCategoryService.listByPage();
        model.addAttribute("ebProductCategories",ebProductCategories);
        model.addAttribute("ebProductCategory",ebProductCategory);
        model.addAttribute("tag",3);
        return "manage/productClass-modify";
    }
    /**
     * 实现分类项修改功能
     * model用于返回操作结果（影响行数）
     * ebProductCategory用于获得要修改项的实体对象
     * 如果父类值为0，则此项修改为父类
     */
    @PostMapping("/productClass-modify")
    public String modify(HttpSession session,Model model,EbProductCategory ebProductCategory){
        Object user = session.getAttribute("lgnUser");
        if (user == null){
            return "redirect:/f-login/to_login";
        }
        EbUser ebUser = (EbUser) user;
        if(ebUser.getEuStatus()!=2){
            return "redirect:/f-index/index";
        }
        model.addAttribute("user",ebUser);
        if (ebProductCategory.getEpcName().trim().length() == 0){
            model.addAttribute("result",0);
            model.addAttribute("tag",3);
            return "manage/manage-result";
        }
        /*
        * 如果要将此项修改为父类，则此项父类为自己
        */
        if (ebProductCategory.getEpcParentId() == 0){
            ebProductCategory.setEpcParentId(ebProductCategory.getEpcId());
        }
        int num = iEbProductCategoryService.updateById(ebProductCategory);
        model.addAttribute("result",num);
        model.addAttribute("tag",3);
        return "manage/manage-result";
    }
    /**
     * 实现分类项删除功能
     * model用于返回操作结果（影响行数）
     * epcId用于获得要删除项的id
     */
    @GetMapping("/delete")
    public String delete(HttpSession session,Model model,int epcId){
        Object user = session.getAttribute("lgnUser");
        if (user == null){
            return "redirect:/f-login/to_login";
        }
        EbUser ebUser = (EbUser) user;
        if(ebUser.getEuStatus()!=2){
            return "redirect:/f-index/index";
        }
        model.addAttribute("user",ebUser);
        EbProductCategory ebProductCategory = iEbProductCategoryService.selectByCondition(epcId);
        int num = iEbProductCategoryService.delete(epcId);
        if(ebProductCategory.getEpcParentId() == epcId && num > 0){
            num = iEbProductCategoryService.deleteAllChild(epcId);
        }
        model.addAttribute("result",num);
        model.addAttribute("tag",3);
        return "manage/manage-result";
    }
}
